import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

import '../common/flatPanel.dart';
import '../entry.dart';
import '../models/topicItem.dart';
import '../parts/megaSiteDialog.dart';
import '../utils/dataSource.dart';
import '../utils/screw.dart';

class MegaSitePage extends StatefulWidget {
  @override
  _MegaSitePageState createState() => _MegaSitePageState();
}

enum RefreshFlag { Initial, TopicView, DetailView }

class _MegaSitePageState extends State<MegaSitePage> {
  final _entry = Entry.MegaSite;
  final _table = 'p_site';
  final _drawHeader = 'DrawHeader';
  final _db = DataSource();
  final _ticks = <int>[];

  var _refreshFlag = RefreshFlag.Initial;
  var _topic = '';
  var _topics = <String>[];
  var _items = <TopicItem>[];
  TopicItem _tapItem;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _topics.add(_drawHeader);
  }

  @override
  void dispose() {
    super.dispose();
    _topics.clear();
    _items.clear();
    _db.close();
  }

  _connectDB() async {
    bool result = await _db.connectDB('local.json');
    if (result) {
      _updateTopics();
    } else {
      Screw.showToast(context, '无法连接到数据库!');
    }
  }

  _updateTopics() async {
    if (_topics.isNotEmpty) _topics.clear();
    _topics.add(_drawHeader);

    if (_db.isConnect) {
      var results = await _db.query('select topic from $_table group by topic');
      var items = <String>[];
      results.forEach((element) {
        items.add(element[0]);
      });
      _topics.addAll(items);
    }

    setState(() {
      _refreshFlag = RefreshFlag.DetailView;
    });
  }

  _updateView() async {
    if (_topic.isEmpty) return;
    var results = await _db.query(
        'select id,label,detail,addition from $_table where topic=?', [_topic]);
    var items = <TopicItem>[];
    results.forEach((element) {
      var item = TopicItem(
          id: element[0],
          topic: _topic,
          label: element[1],
          detail: element[2],
          addition: element[3]);
      items.add(item);
    });

    setState(() {
      _refreshFlag = RefreshFlag.DetailView;
      _items = items;
    });
  }

  Widget _updateFloatingActionButton() {
    switch (_refreshFlag) {
      case RefreshFlag.Initial:
        return FloatingActionButton(
          child: FaIcon(FontAwesomeIcons.plug),
          onPressed: _connectDB,
        );
      default:
        return FloatingActionButton(
          child: Icon(Icons.refresh),
          onPressed: _updateView,
        );
    }
  }

  // https://www.cnblogs.com/sundaysme/p/12579525.html
  Widget _genDrawerHeader() {
    return DrawerHeader(
      decoration: BoxDecoration(color: Colors.lightBlueAccent),
      child: Center(
        child: SizedBox(
          width: 60,
          height: 60,
          child: CircleAvatar(child: Text('Topic')),
        ),
      ),
    );
  }

  _onTapItem() {
    if (_ticks.contains(_tapItem.id)) {
      if (_tapItem.detail.startsWith('http')) Screw.openUrl(_tapItem.detail);
      _ticks.remove(_tapItem.id);
    } else
      _ticks.add(_tapItem.id);
  }

  Widget _genListView() {
    var width = MediaQuery.of(context).size.width;
    var height = MediaQuery.of(context).size.height;
    if (width >= height) {
      return GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          //子组件宽高长度比例
          childAspectRatio: 8.0,
        ),
        itemCount: _items.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(_items[index].label, style: TextStyle(fontSize: 18)),
            subtitle: Text(_items[index].detail),
            onTap: () {
              _tapItem = _items[index];
              _onTapItem();
            },
          );
        },
      );
    } else {
      return ListView.separated(
        itemCount: _items.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(_items[index].label, style: TextStyle(fontSize: 18)),
            subtitle: Text(_items[index].detail),
            onTap: () {
              _tapItem = _items[index];
              _onTapItem();
            },
          );
        },
        separatorBuilder: (context, i) => Divider(),
      );
    }
  }

  _onAddItem() async {
    var inputItem = TopicItem();
    if (_topic.isNotEmpty) inputItem.topic = _topic;

    var item = await showItemAddDialog(context, item: inputItem);
    if (_db.isConnect) {
      var result = await _db.query(
          'insert into $_table (topic,label,detail,addition) values (?,?,?,?)',
          [item.topic, item.label, item.detail, item.addition]);
      if (result.affectedRows == 1) _updateView();
    }
  }

  PopupMenuButton<String> _onPopupMenuButton() {
    return PopupMenuButton<String>(
      offset: Offset(0, 60),
      itemBuilder: (context) {
        return <PopupMenuEntry<String>>[
          PopupMenuItem<String>(
            value: 'updateTopics',
            child: ListTile(
              leading: Icon(Icons.arrow_back_ios_rounded),
              title: Text('刷新列表'),
            ),
          ),
          // PopupMenuDivider(),
          PopupMenuItem<String>(
            value: 'returnHome',
            child: ListTile(
              leading: Icon(Icons.home),
              title: Text('返回首页'),
            ),
          ),
        ];
      },
      onSelected: (value) {
        if (value == 'updateTopics')
          _updateTopics();
        else if (value == 'returnHome') Navigator.pop(context);
      },
    );
  }

  _onEditItem() async {
    if (_tapItem == null || _tapItem.id == 0) return;

    var item = await showItemAddDialog(context, item: _tapItem);
    if (_tapItem.md5() == item.md5()) return;

    if (_db.isConnect) {
      var result = await _db.query(
          'update $_table set topic=?,label=?,detail=?,addition=? where id=?',
          [item.topic, item.label, item.detail, item.addition, item.id]);
      if (result.affectedRows == 1) _updateView();
    }
  }

  _onDeleteItem() async {
    if (_tapItem.id == 0) return;
    if (_db.isConnect) {
      var result =
          await _db.query('delete from $_table where id=?', [_tapItem.id]);
      if (result.affectedRows == 1) _updateView();
    }
  }

  _showDeleteConfirmDialog() async {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('操作确认'),
            content: Text('确定要删除吗？不可恢复！'),
            actions: <Widget>[
              FlatButton(
                child: Text('取消'),
                onPressed: () => Navigator.of(context).pop(),
              ),
              FlatButton(
                child: Text('确定'),
                onPressed: () {
                  _onDeleteItem();
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        });
  }

  _showContextMenu(LongPressEndDetails details) {
    var dx = details.globalPosition.dx;
    var dy = details.globalPosition.dy;
    var width = MediaQuery.of(context).size.width;
    var height = MediaQuery.of(context).size.height;
    var mWidth = 60, mHeight = 50;

    showMenu(
      context: context,
      position: RelativeRect.fromLTRB(dx - mWidth, dy - mWidth,
          width - dy + mHeight, height - dy + mHeight),
      items: <PopupMenuEntry<String>>[
        PopupMenuItem<String>(
          value: 'Edit',
          child: ListTile(
            leading: Icon(Icons.edit),
            title: Text('编辑...'),
            onTap: () => _onEditItem(),
          ),
        ),
        PopupMenuDivider(),
        PopupMenuItem<String>(
          value: 'Delete',
          child: ListTile(
            leading: Icon(Icons.delete),
            title: Text('删除'),
            onTap: () => _showDeleteConfirmDialog(),
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(_entry), actions: <Widget>[
        IconButton(
          icon: Icon(Icons.add),
          onPressed: _onAddItem,
        ),
        _onPopupMenuButton(),
      ]),
      drawer: Drawer(
        child: ListView.builder(
            // padding: EdgeInsets.zero,
            itemCount: _topics.length,
            itemBuilder: (context, index) {
              if (index == 0) return _genDrawerHeader();
              return ListTile(
                  leading: Icon(Icons.title),
                  title: Text(_topics[index], style: TextStyle(fontSize: 18)),
                  onTap: () {
                    _topic = _topics[index];
                    _updateView();
                    Navigator.pop(context);
                  });
            }),
      ),
      body: GestureDetector(
        child: FlatPanel(margin: 8.0, padding: 8.0, child: _genListView()),
        onLongPressEnd: (details) => _showContextMenu(details),
      ),
      floatingActionButton: _updateFloatingActionButton(),
    );
  }
}
